package com.zxbit.flash.ui.activity;

import android.annotation.SuppressLint;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.zxbit.flash.R;
import com.zxbit.flash.adapter.FragmentAdapter;
import com.zxbit.flash.base.BaseTitleActivity;
import com.zxbit.flash.common.Constant;
import com.zxbit.flash.common.DialogManager;
import com.zxbit.flash.common.RouterMap;
import com.zxbit.flash.common.UserInfo;
import com.zxbit.flash.mvpview.UpdateVersionMvpView;
import com.zxbit.flash.presenter.UpdateVersionPresenter;
import com.zxbit.flash.response.UpdateResponse;
import com.zxbit.flash.rxbus.EventMsg;
import com.zxbit.flash.rxbus.Events;
import com.zxbit.flash.rxbus.RxBus;
import com.zxbit.flash.ui.fragment.HomeFragment;
import com.zxbit.flash.ui.fragment.MineFragment;
import com.zxbit.flash.utils.ApkUtils;
import com.zxbit.flash.utils.AssetsUtils;
import com.zxbit.flash.utils.ToastUtils;
import com.zxbit.flash.view.MyViewPager;
import com.zxbit.flash.view.dialog.UpdateVersionDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

@Route(name = "首页", path = RouterMap.MAIN_ACTIVITY_PAGE)
public class MainActivity extends BaseTitleActivity implements UpdateVersionMvpView {

    @BindView(R.id.viewpager)
    MyViewPager viewPager;
    @BindView(R.id.layout_home)
    LinearLayout layoutHome;
    @BindView(R.id.layout_mine)
    LinearLayout layoutMine;

    private FragmentAdapter fragmentAdapter;
    private UpdateVersionDialog updateVersionDialog;
    private UpdateVersionPresenter updateVersionPresenter;

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        viewPager.setAdapter(getFragmentAdapter());
        viewPager.setOffscreenPageLimit(2);
        viewPager.setCurrentItem(0);
        layoutHome.setSelected(true);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onUIReady() {
        AssetsUtils.copyDB();
        updateVersionPresenter = new UpdateVersionPresenter(this);
        RxBus.getInstance().toObservable().map(new Function<Object, EventMsg>() {
            @Override
            public EventMsg apply(Object o) throws Exception {
                return (EventMsg) o;
            }
        }).subscribe(new Consumer<EventMsg>() {
            @Override
            public void accept(EventMsg eventMsg) throws Exception {

                if (Events.UPDATE.equals(eventMsg.getMsg())) {
                    // 检查版本更新
                    updateVersionPresenter.checkGooglePlayUpdate();
                } else if (Events.LOGOUT.equals(eventMsg.getMsg())) {
                    viewPager.setCurrentItem(0);
                    layoutHome.setSelected(true);
                    layoutMine.setSelected(false);
                }

            }
        });
    }

    private FragmentAdapter getFragmentAdapter() {
        if (fragmentAdapter == null) {
            List<Fragment> fragmentList = new ArrayList<>();
            HomeFragment homeFragment = new HomeFragment();
            MineFragment mineFragment = new MineFragment();
            fragmentList.add(homeFragment);
            fragmentList.add(mineFragment);
            fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragmentList);
        }
        return fragmentAdapter;
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_main;
    }

    @OnClick({R.id.layout_home, R.id.layout_mine})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_home:
                viewPager.setCurrentItem(0);
                layoutHome.setSelected(true);
                layoutMine.setSelected(false);
                break;
            case R.id.layout_mine:
                if (UserInfo.isLogin()) {
                    viewPager.setCurrentItem(1);
                    layoutHome.setSelected(false);
                    layoutMine.setSelected(true);
                } else {
                    ARouter.getInstance().build(RouterMap.FACEBOOKLOGIN).navigation();
                    ToastUtils.showShort(this, getResources().getString(R.string.login_not_login));
                }
                break;
        }
    }

    @Override
    public void onGetDataNext(final UpdateResponse updateResponse) {
        if (updateResponse.getStatus() == Constant.HTTP_OK && updateResponse.hasData()) {
            if (updateVersionDialog == null) {
                updateVersionDialog = new UpdateVersionDialog(this, R.style.normal_dialog);
            }
            updateVersionDialog.setTitle(getStringResource(R.string.update_dialog_title));
            updateVersionDialog.setContent(getStringResource(R.string.update_dialog_code) +
                    updateResponse.getData().getAppVersion() + "\n" + updateResponse.getData()
                    .getDesc());
            if (updateResponse.getData().isUpdate()) {
                updateVersionDialog.setCancelable(false);
            } else {
                updateVersionDialog.setCancelable(true);
            }
            updateVersionDialog.setNormalClickListener(new UpdateVersionDialog
                    .NormalClickListener() {
                @Override
                public void onConfirmClick() {
                    if (!updateResponse.getData().isUpdate()) {
                        DialogManager.getManager().dismissDialog(updateVersionDialog);
                    }
                    ApkUtils.launchAppDetail(MainActivity.this, updateResponse.getData().getpName());
                }
            });
            DialogManager.getManager().showDialogStack(updateVersionDialog);
        }
    }

    @Override
    public void onGetDataError(Throwable throwable) {
        dismissLoadingView();
    }
}
